import { Injectable } from '@nestjs/common'
import { PassportStrategy } from '@nestjs/passport'
import { Strategy, ExtractJwt, StrategyOptions } from 'passport-jwt'
import config from '../config'

@Injectable()
export class JwtStrategy extends PassportStrategy(Strategy, 'jwt') {
  constructor() {
    super({
      jwtFromRequest: ExtractJwt.fromHeader('token'),
      secretOrKey: config.server.scret,
      ignoreExpiration: false,
    } as StrategyOptions)
  }

  async validate(payload: any): Promise<any> {
    // payload解密jwtService.sign({ username, id: user._id })的数据;
    // Passport 将基于 validate() 方法的返回值构建一个user 对象，并将其作为属性附加到请求对象上。
    // 返回值会挂载到 controller层 @Request() req.user
    return { id: payload.id, username: payload.username }
  }
}
